var stepId = $CertusJsonAjax.getStepInstanceId();
var processId = $CertusJsonAjax.getProInstanceId();

this.getUser = function (compCode) {
    $("#dyUserName").val("");
    $("#dyUserId").val("");
    $("#deptCode").val("");
    // 开启
    var index = layer.load(2);
    $CertusFormAjax.ajax("findUsersByComp",{"compCode":compCode},function (response) {
        var nhlTeams = [];
        var data = response.data;
        for (var i=0;i<data.length;i++){
            var arr={};
            arr.name=data[i].userName;
            arr.id = data[i].userId;
            nhlTeams.push(arr);
        }
        //自动补全
        var nhl = $.map(nhlTeams, function (obj) {
            return {
                value: obj.name+"("+obj.id+")",
                data: { category: obj.id }
            };
        });
        // Initialize autocomplete with local lookup:
        $('#dyUserName').devbridgeAutocomplete({
            lookup: nhl,
            minChars: 1,
            onSelect: function (suggestion) {
                $("#dyUserId").val(suggestion.data.category);
                getDep_1(suggestion.data.category,"");
            },
            showNoSuggestionNotice: true,
            noSuggestionNotice: 'Sorry, no matching results'
        });
        //关闭
        layer.close(index);
    });
};

this.getProContract = function (proId,contractId) {
    $CertusFormAjax.ajax("contractProgresss",{"projId":proId},function (response) {
        var data = response.data;
        $("#contractId").html("");
        $("#contractId").append('<option value="">请选择</option>');
        for (var i=0;i<data.length;i++){
            var ctinfo = data[i].contractInfo;
            $("#contractId").append("<option value='"+ctinfo.contractNo+"'>"+ctinfo.contractNo+"</option>")
        }
        if (contractId!=""){
            $("#contractId").val(contractId);
        }
    });
};

$CertusFormAjax.ajax("findSeProList",{},function(response){
    var nhlTeams = [];
    var data = response.data;
    for (var i=0;i<data.length;i++){
        var arr={};
        arr.name=data[i].proName;
        arr.id = data[i].id;
        nhlTeams.push(arr);
    }
    //自动补全
    var nhl = $.map(nhlTeams, function (obj) {
        return {
            value: obj.name,
            data: { category: obj.id }
        };
    });
    // Initialize autocomplete with local lookup:
    $('#proName').devbridgeAutocomplete({
        lookup: nhl,
        minChars: 1,
        onSelect: function (suggestion) {
            $("#proId").val(suggestion.data.category);
            getProContract(suggestion.data.category,"");
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: 'Sorry, no matching results'
    });

});
//所属公司
// CertusFormAjax.ajax("companyListByViewCode",{},function (response) {
//     $scope.comp = JSON.parse(response.data);
// });

this.getDep_1 = function (userId,deptCode) {
    $CertusFormAjax.ajax('initDepts',{"userId":userId},function (response) {
        var data = response.data;
        $$scope.depts = data;
        // if (data.length==1){
        //     $("#deptCode").attr("disabled","disabled");
        // }
        // $scope.deptCode = data[0].departmentCode;
        if (deptCode!=""){
            $$scope.deptCode = deptCode;
        }
    });
};

// 展示隐藏
function coladd() {
    var status = $("#addloc").css('display');
    if (status === "block") {
        $("#addloc").hide();
    } else {
        $("#addloc").show();
    }
}

this.clearTab = function () {
    $("#dyType").val("kf");
    $("#dyUserId").val("");
    $("#dyUserName").val("");
    $("#deptCode").val("");
    $("#workStart").val("");
    $("#workEnd").val("");
    $("#comments").val("");
    $("#invoiceSl").val("");
};
//临时ID
var nid = 1000;
var ppid = 1;
var userArr = [];

this.loadlb = function (paramArr) {
    userArr = paramArr;
    $("#userlistContainer").empty();
    var userlistColumns = [{
        id: 'deptName',
        title: '借调部门',
        type: 'string',
        width: 150,
        columnClass: 'text-center'
    }, {
        id: 'loanType',
        title: '人员类别',
        type: 'string',
        width: 75,
        columnClass: 'text-center',
    }, {
        id: 'userName',
        title: '人员姓名',
        type: 'string',
        width: 75,
        columnClass: 'text-center'
    }, {
        id: 'workStart',
        title: '开始日期',
        type: 'string',
        columnClass: 'text-center',
        resolution: function (value, record, column, grid, dataNo, columnNo) {
            var date = new Date(value);
            var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
            return content;
        }
    }, {
        id: 'workEnd',
        title: '结束日期',
        type: 'string',
        columnClass: 'text-center',
        resolution: function (value, record, column, grid, dataNo, columnNo) {
            var date = new Date(value);
            var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd");
            return content;
        }
    },{
        id: 'invoice',
        title: '投入占比',
        type: 'string',
        width: 90,
        columnClass: 'text-center',
        resolution: function (value, record, column, grid, dataNo, columnNo) {
            var content = value + '%';
            return content;
        }
    }, {
        id: 'comments',
        title: '工作任务',
        type: 'string',
        columnClass: 'text-center',
    }, {
        id: 'operation',
        title: '操作',
        width: 130,
        type: 'string',
        columnClass: 'text-center',
        resolution: function (value, record, column, grid, dataNo, columnNo) {
            var content = '';
            // content += '<button class="btn btn-xs btn-success" onclick="coladd()"><i class="fa fa-edit"></i>  编辑</button>';
            // content += '  ';
            content += '<button class="btn btn-xs btn-danger" onclick="delArr(\''+record.pid+'\')"><i class="fa fa-trash-o"></i>  删除</button>';
            content+=' ';
            content += '<button class="btn btn-xs btn-info" onclick="editArr(\''+record.id+'\')"><i class="fa fa-trash-o"></i> 编辑</button>';
            return content;
        }
    }];
    var userlistOption = {
        lang: 'zh-cn',
        ajaxLoad: false,
        exportFileName: '人员借调列表',
        datas: paramArr,
        columns: userlistColumns,
        gridContainer: 'userlistContainer',
        tools: ''
    };
    var userlistGrid = $.fn.dlshouwen.grid.init(userlistOption);
    userlistGrid.load();
};
var did = "";
function delArr(id) {
    layer.confirm('确认删除此数据？', {
        btn: ['确定', '取消'] //按钮
    }, function (index) {
        //删除
        var arr ={};
        for (var i=0;i<userArr.length;i++){
            if (userArr[i].pid == id){
                arr = userArr[i];
            }
        }
        userArr.splice($.inArray(arr, userArr), 1);
        loadlb(userArr);
        if (isNaN(id)){
            did+=","+id;
        };
        layer.close(index);
        clearTab();
        $("#addloc").hide();
    });
};

function editArr(id) {
    clearTab();
    $("#addloc").show();
    var arr ={};
    for (var i=0;i<userArr.length;i++){
        if (userArr[i].id ==id){
            arr = userArr[i];
        }
    }
    getDep_1(arr.userId,arr.deptCode);

    $("#dyType").val(arr.loanType);
    $("#dyUserId").val(arr.userId);
    $("#dyUserName").val(arr.userName);
    var beginTime = new Date(arr.workStart);
    var nfordate = $.fn.dlshouwen.grid.tools.dateFormat(beginTime, "yyyy-MM-dd");
    $("#workStart").val(nfordate);
    var endTime = new Date(arr.workEnd);
    var endDate = $.fn.dlshouwen.grid.tools.dateFormat(endTime, "yyyy-MM-dd");
    $("#workEnd").val(endDate);
    $("#comments").val(arr.comments);
    $("#invoiceSl").val(arr.invoice);
}

$CertusFormAjax.ajax('findRhLocs',{"processId":processId},function (response) {
    var tlmBean = response.data.tlmBean;
    $("#addloc").hide();
    $$scope.companys = tlmBean.companyCode;
    $$scope.id = tlmBean.id;
    getUser(tlmBean.companyCode);
    $$scope.proName = tlmBean.proName;
    getProContract(tlmBean.proId,tlmBean.contractId);
    $$scope.proId = tlmBean.proId;
    $$scope.loanComments = tlmBean.loanComments;

    var personList = response.data.personList;
    loadlb(personList);
});

$(".sumbit").on('click',function () {
    if (userArr.length==0){
        layer.msg("至少提交一个借调人员");
        return;
    }
    var companyId = $("#companys").val();
    if (companyId==""){
        layer.msg("公司不能为空");
        return;
    }
    var companyName = $('#companys option:selected').text();
    var proId = $("#proId").val();
    if (proId==""){
        layer.msg("归属项目不能为空");
        return;
    }
    var proName = $("#proName").val();
    var contractId = $("#contractId").val();
    // if (contractId==""){
    //     layer.msg("合同不能为空");
    //     return;
    // }
    var loanComments = $("#loanComments").val();
    var arr ={};
    arr.companyId = companyId;
    arr.companyName = companyName;
    arr.proId = proId;
    arr.proName = proName;
    arr.contractId = contractId;
    arr.loanComments = loanComments;
    arr.userList = userArr;
    arr.did = did;

    $CertusFormAjax.ajax('editLoan',{"id":$$scope.id,"stepId":stepId,
        "param":JSON.stringify(arr),"processId":processId},function () {
        layer.msg("审批成功！");
        window.history.back();
    });
});


// 新增人员
function subpro() {
    var dyType = $("#dyType").val();
    var dyUserId = $("#dyUserId").val();
    if (dyUserId==""){
        layer.msg("借调人员不能为空");
        return;
    }
    var deptCode = $("#deptCode").val();
    if (deptCode==""){
        layer.msg("借调人员归属部门不能为空");
        return;
    }
    var workStart = $("#workStart").val();
    if (workStart==""){
        layer.msg("开始日期不能为空");
        return;
    }
    var workEnd = $("#workEnd").val();
    if (workEnd==""){
        layer.msg("结束日期不能为空");
        return;
    }
    var beginTimes = new Date(workStart.replace("/", "-").replace("/", "-"));
    var endTimes = new Date(workEnd.replace("/", "-").replace("/", "-"));
    if (beginTimes>endTimes){
        layer.msg("开始日期不能大于结束日期",{time:1000});
        return;
    }
    var comments = $("#comments").val();
    if (comments==""){
        layer.msg("工作任务不能为空");
        return;
    }
    var invoiceSl = $("#invoiceSl").val();
    if (invoiceSl==""){
        layer.msg("投入百分比不能为空");
        return;
    }

    //判断是否已经存在
    var delArr={};
    for (var i=0;i<userArr.length;i++){
        if (userArr[i].userId == dyUserId){
            delArr = userArr[i];
            userArr.splice($.inArray(delArr, userArr), 1);
        }
    }
   

    var arr = {};
    arr.loanType = dyType;
    arr.userId = dyUserId;
    arr.userName = $("#dyUserName").val();
    arr.deptCode = deptCode;
    arr.deptName = $('#deptCode option:selected').text();
    arr.workStart = workStart;
    arr.workEnd = workEnd;
    arr.comments = comments;
    arr.invoice = invoiceSl;
    arr.id = nid;
    arr.pid = ppid;
    userArr.push(arr);
    nid++;
    ppid++;
    loadlb(userArr);
    clearTab();
}
